﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;
using System.Xml;
using System.Collections;

public class PredicateBuilder<T>
{
    private static Expression Zero = Expression.Constant(0);
    private static Expression True = Expression.Constant(true);
    private static Expression False = Expression.Constant(false);

    /// <summary>
    /// 创建Linq表达式
    /// </summary>
    /// <param name="columns">可查询的字段</param>
    /// <param name="paramters">参数值</param>
    /// <param name="varName">Linq变量名</param>
    /// <returns></returns>
    public static Expression<Func<T, bool>> CreatePredicate(string[] columns, string param, string varName)
    {
        Expression expression = null;
        ParameterExpression parameter = Expression.Parameter(typeof(T), varName);

        foreach (string c in columns)
        {
            Expression exp = null;
            Expression property = Expression.Property(parameter, c);

            string[] vs = param.Split(' ');
            foreach (string v in vs)
            {
                if (v != "")
                {
                    Expression e1 = Expression.Call(
                        property,
                        typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),
                        new Expression[] { Expression.Constant(v) });

                    exp = exp == null ? e1 : Expression.Or(exp, e1);
                }
            }

            expression = exp == null ? expression :
                expression == null ? exp : Expression.Or(expression, exp);
        }

        return expression == null ? null : Expression.Lambda<Func<T, bool>>(expression, parameter);
    }
}